package controllers

import (
	"github.com/gorilla/websocket"
	"log"
)

func init() {
	go Chat()
}

func Chat() {
	for {
		// 从广播频道抓取下一条消息
		msg := <-broadcast
		// 将其发送到当前连接的每个客户端
		for client := range clients {
			err := client.WriteJSON(msg)
			if err != nil {
				log.Printf("error: %v", err)
				client.Close()
				delete(clients, client)
			}
		}
	}
}

func Connect(ws *websocket.Conn) {
	// 注册新的客户端
	clients[ws] = true
}

func Leave(ws *websocket.Conn) {
	delete(clients, ws)
}